import { getPluginsList } from "./build/plugins";
import { include, exclude } from "./build/optimize";
import {
  type UserConfigExport,
  type ConfigEnv,
  loadEnv,
  defineConfig
} from "vite";
import {
  root,
  alias,
  wrapperEnv,
  pathResolve,
  __APP_INFO__
} from "./build/utils";

export default defineConfig(({ mode }: ConfigEnv): UserConfigExport => {
  const { VITE_CDN, VITE_PORT, VITE_COMPRESSION, VITE_PUBLIC_PATH } =
    wrapperEnv(loadEnv(mode, root));

  return {
    base: VITE_PUBLIC_PATH || "./",
    root,
    resolve: {
      alias
    },
    // 服务端渲染
    server: {
      // 端口号
      port: VITE_PORT,
      host: true,
      // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
      proxy: {
        "/api": {
          // target: "https://huayiapp.email/front",
          target: "http://127.0.0.1:8002/admin",
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, ""),
          secure: false,
          ws: true,
          headers: {
            Connection: "keep-alive"
          }
        },
        "/ai-api": {
          target: "http://169.254.108.247:5000",
          changeOrigin: true,
          rewrite: path => path.replace(/^\/ai-api/, ""),
          secure: false
        },
        // 添加视频代理配置，用于解决跨域问题
        "/video-proxy": {
          target: "https://v9-vvecloud.yangyi08.com",
          changeOrigin: true,
          rewrite: path => {
            const url = new URL(path, "https://v9-vvecloud.yangyi08.com");
            const targetUrl = url.searchParams.get("url") || "";
            return targetUrl.replace("https://v9-vvecloud.yangyi08.com", "");
          },
          headers: {
            "User-Agent":
              "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
          },
          secure: false
        }
      },
      // 预热文件以提前转换和缓存结果，降低启动期间的初始页面加载时长并防止转换瀑布
      warmup: {
        clientFiles: ["./index.html", "./src/{views,components}/*"]
      }
    },
    plugins: getPluginsList(VITE_CDN, VITE_COMPRESSION),
    // https://cn.vitejs.dev/config/dep-optimization-options.html#dep-optimization-options
    optimizeDeps: {
      include,
      exclude
    },
    build: {
      // https://cn.vitejs.dev/guide/build.html#browser-compatibility
      target: "es2015",
      sourcemap: false,
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 4000,
      rollupOptions: {
        input: {
          index: pathResolve("./index.html", import.meta.url)
        },
        // 静态资源分类打包
        output: {
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]"
        }
      },
      // 确保资源正确加载
      assetsDir: "assets",
      outDir: "dist",
      emptyOutDir: true,
      manifest: true,
      // 添加资源内联限制
      assetsInlineLimit: 4096,
      // 确保正确的 MIME 类型
      cssCodeSplit: true,
      // 添加浏览器兼容性配置
      cssTarget: ["chrome61"]
    },
    define: {
      __INTLIFY_PROD_DEVTOOLS__: false,
      __APP_INFO__: JSON.stringify(__APP_INFO__)
    },
    css: {
      preprocessorOptions: {
        scss: {
          // 移除全局导入，改为在需要的地方单独导入
          // additionalData: `@import "@/styles/mixins.scss";`
        }
      },
      // 添加 CSS 模块配置
      modules: {
        scopeBehaviour: "local"
      },
      // 确保 CSS 提取
      devSourcemap: true
    }
  };
});
